import React, {useEffect} from "react";
import Cookie from "react-cookies";
import {useSearchParams,useNavigate} from "react-router-dom";
import request from "@/utils/ajax/request";

const Login = () =>{
    //路由切换
    const navigate = useNavigate()
    // 查询url字符串的值
    const [searchParams] = useSearchParams();
    // oAuth登录
    const loginOAuth = () => {
        let  url='https://gitee.com/oauth/authorize?client_id=ed08944534132f25fba290b355da46ce85f7a522d33f6b44f8182169fedbe1aa&redirect_uri=http://localhost:3000/login&response_type=code';
        Cookie.save('loginType','gite')
        window.location.href = url;//跳转第三方登录接口并返回code码
    }
    const loginType = Cookie.load('loginType');//获取登录type
    const access_token = Cookie.load('access_token') //获取access_token
    useEffect(() => {
        //access_token纯在跳转个人中心
        if(!!access_token ){
            navigate(window.base.config.path+'personal')
        }else if (loginType !== undefined){
            getAccessToken()
        }
    }, );
    //拿到code码兑换access_token
    const getAccessToken = ()=>{
        let code = searchParams.get("code")
        let url = window.location.href; //获取当前连接
        let hasCode = url.includes('?code=')//查看当前链接是否包含code
        if (hasCode){
            let newUrl = url.split("?code="); //已?code=临界线分割链接为数组
            window.history.replaceState({}, null,newUrl[0]) //只修改链接不刷新页面
            switch (loginType){
                case 'gite':
                    let url=`https://gitee.com/oauth/token?grant_type=authorization_code&code=${code}&client_id=ed08944534132f25fba290b355da46ce85f7a522d33f6b44f8182169fedbe1aa&redirect_uri=http://localhost:3000/login&client_secret=c228e9b2251c84b37348436916a8c50ea463486da349fa3fb007ce93259b4187`;
                    request(url,'post').then((res)=>{
                        Cookie.save('access_token',res.access_token);
                        Cookie.save('refresh_token',res.refresh_token);
                        Cookie.save('accessIdList',['10000', '10001', '10002', '10009']);
                        navigate(window.base.config.path+'personal')
                    })
                    return;
                default:
                    return;
            }
        }
    }
    return(
        <div>
            <div onClick={loginOAuth.bind(this,111)}>OAuth登录</div>
        </div>
    )
}
export default Login